#!/usr/bin/env python
#-*- coding:utf-8 -*-

# file:verify_code.py
# author:ytytyt
# datetime:2022/6/21 15:52
# software: PyCharm
'''
this is functiondescription
'''
# import module your need
import random
from PIL import Image, ImageDraw, ImageFont

def gen_verify_img(text):
    bg_color = (random.randrange(20, 120), random.randrange(20, 120), random.randrange(150, 255))
    width = 400
    height = 100
    im = Image.new('RGB',(width,height),bg_color)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 构造字体对象
    font = ImageFont.truetype('./cambriai.ttf', 100)
    # font = ImageFont.load_default().font
    # 构造字体颜色
    fontcolor = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((random.randint(10, 30), (random.randint(0, 10))), text[0], font=font, fill=fontcolor)
    draw.text((random.randint(90, 130), (random.randint(0, 10))), text[1], font=font, fill=fontcolor)
    draw.text((random.randint(180, 230), (random.randint(0, 10))), text[2], font=font, fill=fontcolor)
    draw.text((random.randint(270, 330), (random.randint(0, 10))), text[3], font=font, fill=fontcolor)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 10000):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))
        draw.point(xy, fill=fill)

    #释放画笔
    del draw
    # im.show()
    return text
    # im.save(f'./{text}.png','png')

def get_verifycode():
    string = ''
    #随机选取4个值作为验证码
    rand_str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    for i in range(0, 4):
        string += rand_str[random.randrange(0, len(rand_str))]
    code = gen_verify_img(string)
    return code
get_verifycode()